import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Drawer, message, Modal, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import {
  addInterfaceInfoUsingPost,
  deleteInterfaceInfoUsingPost,
  listInterfaceInfoByPageUsingPost,
  offlineInterfaceInfoUsingPost,
  onlineInterfaceInfoUsingPost,
  updateInterfaceInfoUsingPost,
} from '@/services/sutongapi-backend/interfaceInfoController';
import CreateUpdateForm from '@/pages/Admin/InterfaceInfo/components/CreateUpdateForm';
import InterfaceParamTable from '@/pages/Admin/InterfaceParam/components/Table';

/**
 * 添加接口
 *
 * @param fields
 */
const handleAdd = async (fields: API.InterfaceInfo) => {
  const hide = message.loading('正在添加');
  try {
    await addInterfaceInfoUsingPost({
      ...fields,
    } as API.InterfaceInfoAddRequest);
    hide();
    message.success('添加成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '添加失败，请重试');
    return false;
  }
};

/**
 * 更新接口
 *
 * @param fields
 */
const handleUpdate = async (fields: API.InterfaceInfo) => {
  const hide = message.loading('正在修改');
  try {
    await updateInterfaceInfoUsingPost({
      ...fields,
    } as API.InterfaceInfoUpdateRequest);
    hide();
    message.success('修改成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '修改失败，请重试');
    return false;
  }
};

/**
 * 删除接口
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.InterfaceInfo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    // 性能问题
    for (let row of selectedRows) {
      await deleteInterfaceInfoUsingPost({
        id: row.id ?? 0,
      });
    }
    hide();
    message.success('删除成功，将很快刷新');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '删除失败，请重试');
    return false;
  }
};

/**
 * 发布接口
 *
 * @param selectedRows
 */
const handleOnline = async (selectedRows: API.InterfaceInfo[]) => {
  const hide = message.loading('正在发布');
  if (!selectedRows) return true;
  try {
    for (let row of selectedRows) {
      await onlineInterfaceInfoUsingPost({
        id: row.id ?? 0,
      });
    }
    hide();
    message.success('发布成功，将很快刷新');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '发布失败，请重试');
    return false;
  }
};

/**
 * 下线接口
 *
 * @param selectedRows
 */
const handleOffline = async (selectedRows: API.InterfaceInfo[]) => {
  const hide = message.loading('正在下线');
  if (!selectedRows) return true;
  try {
    for (let row of selectedRows) {
      await offlineInterfaceInfoUsingPost({
        id: row.id ?? 0,
      });
    }
    hide();
    message.success('下线成功，将很快刷新');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '下线失败，请重试');
    return false;
  }
};

const InterfaceInfo: React.FC = () => {
  const [modalOpen, handleModalOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('');
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);
  const actionRef = useRef<ActionType>();

  const [paramsFormVisible, setParamsFormVisible] = useState<boolean>(false);
  const [paramType, setParamType] = useState<number>();

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      tip: '主键',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: 'URL',
      dataIndex: 'url',
      valueType: 'text',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '请求参数',
      dataIndex: 'option',
      valueType: 'option',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              setParamsFormVisible(true);
              setCurrentRow(record);
              setParamType(0);
            }}
          >
            详情
          </a>
        );
      },
    },
    {
      title: '响应参数',
      dataIndex: 'option',
      valueType: 'option',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              setParamsFormVisible(true);
              setCurrentRow(record);
              setParamType(1);
            }}
          >
            详情
          </a>
        );
      },
    },
    {
      title: '请求头参数',
      dataIndex: 'option',
      valueType: 'option',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              setParamsFormVisible(true);
              setCurrentRow(record);
              setParamType(2);
            }}
          >
            详情
          </a>
        );
      },
    },
    {
      title: '响应头参数',
      dataIndex: 'option',
      valueType: 'option',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              setParamsFormVisible(true);
              setCurrentRow(record);
              setParamType(3);
            }}
          >
            详情
          </a>
        );
      },
    },
    {
      title: '请求方式',
      dataIndex: 'method',
      valueType: 'text',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Error',
        },
        1: {
          text: '开启',
          status: 'Success',
        },
      },
    },
    {
      title: '创建人',
      dataIndex: 'userId',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      ellipsis: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      ellipsis: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '120px',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleModalOpen(true);
            setCurrentRow(record);
            setModalTitle('修改接口');
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="delete"
          title="删除接口"
          description="您确定要删除此接口吗？"
          onConfirm={async () => {
            const res = await handleRemove([record]);
            if (res) {
              actionRef.current?.reloadAndRest?.();
            }
          }}
        >
          <a style={{ color: 'red' }} key="delete">
            删除
          </a>
        </Popconfirm>,
        record.status === 0 ? (
          <a
            key="online"
            style={{ color: 'green' }}
            onClick={async () => {
              const res = await handleOnline([record]);
              if (res) {
                actionRef.current?.reloadAndRest?.();
              }
            }}
          >
            发布
          </a>
        ) : null,
        record.status === 1 ? (
          <a
            key="offline"
            style={{ color: 'red' }}
            onClick={async () => {
              const res = await handleOffline([record]);
              if (res) {
                actionRef.current?.reloadAndRest?.();
              }
            }}
          >
            下线
          </a>
        ) : null,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.InterfaceInfo, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow({});
              setModalTitle('新建接口');
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort) => {
          let queryParams: any = {
            ...params,
          };

          // 如果存在排序信息，对数据进行排序
          if (sort && Object.keys(sort).length) {
            const [[sortField, sortOrder]] = Object.entries(sort);
            queryParams.sortField = sortField;
            queryParams.sortOrder = sortOrder;
          }
          const res = await listInterfaceInfoByPageUsingPost({
            ...queryParams,
          });

          return {
            data: res.data?.records || [],
            success: res.code === 0,
            total: res.data?.total || 0,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      <CreateUpdateForm
        title={modalTitle}
        open={modalOpen}
        onOpenChange={handleModalOpen}
        initialValues={currentRow}
        onFinish={async (value) => {
          let res = undefined;
          if (value.id) {
            res = await handleUpdate(value as API.InterfaceInfo);
          } else {
            res = await handleAdd(value as API.InterfaceInfo);
          }
          if (res) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />

      <Modal
        width="70%"
        destroyOnClose={true}
        open={paramsFormVisible}
        onOk={() => {
          setParamsFormVisible(false);
        }}
        onCancel={() => {
          setParamsFormVisible(false);
        }}
      >
        <InterfaceParamTable
          interfaceInfoId={currentRow?.id as number}
          type={paramType as number}
          search={false}
        />
      </Modal>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.InterfaceInfo>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.InterfaceInfo>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default InterfaceInfo;
